cmake_minimum_required(VERSION 3.14.0)

include_guard(GLOBAL)

function(http_archive)
  if(${ARGC} EQUAL 1)
    set(REPO_INFO_JSON ${ARGV0})
  else()
    if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/http_archive.json)
      set(REPO_INFO_JSON ${CMAKE_CURRENT_SOURCE_DIR}/http_archive.json)
    else()
      unset(REPO_INFO_JSON)
    endif()
  endif()

  if(REPO_INFO_JSON)
    file(RELATIVE_PATH PROJ_REL_PATH ${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR})
    set(DOWNLOAD_DIR ${CMAKE_SOURCE_DIR}/external/${PROJ_REL_PATH})
    add_custom_command(
      OUTPUT ${DOWNLOAD_DIR}/.http_archive.json
      COMMAND python3 ${CMAKE_SOURCE_DIR}/script/http_archive.py ${REPO_INFO_JSON} --output_dir ${DOWNLOAD_DIR}
      DEPENDS ${CMAKE_SOURCE_DIR}/script/http_archive.py ${REPO_INFO_JSON}
    )
    add_custom_target(${NS}__${PROJECT_NAME}__repo
      DEPENDS ${DOWNLOAD_DIR}/.http_archive.json
    )
    set(DOWNLOAD_DIR ${DOWNLOAD_DIR} PARENT_SCOPE)
  else()
    message(FATAL_ERROR "http_archive.json missing for ${NS}__${PROJECT_NAME}__repo!")
  endif()
endfunction()
